package com.example.choupaiapp.main.activity.mine;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.activity.home.OtherInfoActivity;
import com.example.choupaiapp.main.activity.message.ByIdDetailActivity;
import com.example.choupaiapp.main.bean.SplashBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.WalletListBean;
import com.example.choupaiapp.main.constant.Url;
import com.gcssloop.widget.RCImageView;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/11/19.
 */

public class MineWalletActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.listview)
    XListView listview;
    private UserInfoBean userInfoBean;
    private QuickAdapter<WalletListBean.PageBean.ListBean> quickAdapter;
    private int pageNum = 1;
    private int pageSize = 20;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private SplashBean mSplashBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_wallet);
    }

    @Override
    protected void initView() {
        setTitle("我的钱包");
        right_tv.setText("更多任务");

        EventBus.getDefault().register(this);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
        money.setText(userInfoBean.getUser().getBalance().stripTrailingZeros().toPlainString() + "");

        quickAdapter = new QuickAdapter<WalletListBean.PageBean.ListBean>(context, R.layout.item_wallet_detail) {
            @Override
            protected void convert(BaseAdapterHelper helper, WalletListBean.PageBean.ListBean item) {
                RelativeLayout item_rl = helper.getView(R.id.item_rl);
                CircleImageView head_photo = helper.getView(R.id.head_photo);
                RCImageView photo = helper.getView(R.id.photo);
                head_photo.setVisibility(View.INVISIBLE);
                photo.setVisibility(View.INVISIBLE);
                TextView money = helper.getView(R.id.money);
                TextView time = helper.getView(R.id.time);
                time.setText(item.getApplyTime());
                TextView name = helper.getView(R.id.name);

                if (item.getType() == 1) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("id", item.getContentId() + "");
                            startActivity(ByIdDetailActivity.class, bundle1);
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(item.getTitle())) {
                        name.setText("[追加奖励] " + item.getTitle());
                    } else {
                        if ("1".equals(item.getContentType() + "")) {
                            name.setText("[追加奖励] 视频");
                        } else if ("2".equals(item.getContentType() + "")) {
                            name.setText("[追加奖励] 图片");
                        } else {
                            name.setText("[追加奖励] 内容已删除");
                        }
                    }
                    money.setText("+" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(userInfoBean.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    helper.setText(R.id.state, "已奖励");
                } else if (item.getType() == 2) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    name.setText("[微信提现]" + userInfoBean.getUser().getNickname());
                    money.setText("" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(userInfoBean.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    if (item.getStatus() == 0) {
                        helper.setText(R.id.state, "处理中");
                    } else {
                        helper.setText(R.id.state, "已到账");
                    }
                } else if (item.getType() == 3) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            startActivity(MineEnergyActivity.class);
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    name.setText("[能量兑换]" + userInfoBean.getUser().getNickname());
                    money.setText("+" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(userInfoBean.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    helper.setText(R.id.state, "已到账");
                } else if (item.getType() == 4) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("userId", item.getUser().getUserId() + "");
                            startActivity(OtherInfoActivity.class, bundle1);
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("userId", item.getUser().getUserId() + "");
                            startActivity(OtherInfoActivity.class, bundle1);
                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    name.setText("[邀请奖励]" + item.getUser().getNickname());
                    money.setText("+" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(item.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    helper.setText(R.id.state, "已奖励");
                } else if (item.getType() == 5) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    name.setText("[新人奖励]" + userInfoBean.getUser().getNickname());
                    money.setText("+" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(userInfoBean.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    helper.setText(R.id.state, "已奖励");
                } else if (item.getType() == 6) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("id", item.getContentId() + "");
                            startActivity(ByIdDetailActivity.class, bundle1);
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("userId", item.getUser().getUserId() + "");
                            startActivity(OtherInfoActivity.class, bundle1);
                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(item.getTitle())) {
                        name.setText("[好友发布] " + item.getTitle());
                    } else {
                        if ("1".equals(item.getContentType() + "")) {
                            name.setText("[好友发布] 视频");
                        } else if ("2".equals(item.getContentType() + "")) {
                            name.setText("[好友发布] 图片");
                        } else {
                            name.setText("[好友发布] 内容已删除");
                        }
                    }
                    money.setText("+" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(item.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    helper.setText(R.id.state, "已奖励");
                } else if (item.getType() == 7) {
                    item_rl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("id", item.getContentId() + "");
                            startActivity(ByIdDetailActivity.class, bundle1);
                        }
                    });
                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        }
                    });
                    head_photo.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(item.getTitle())) {
                        name.setText("[发帖奖励] " + item.getTitle());
                    } else {
                        if ("1".equals(item.getContentType() + "")) {
                            name.setText("[发帖奖励] 视频");
                        } else if ("2".equals(item.getContentType() + "")) {
                            name.setText("[发帖奖励] 图片");
                        } else {
                            name.setText("[发帖奖励] 内容已删除");
                        }
                    }
                    money.setText("+" + item.getMoney().stripTrailingZeros().toPlainString() + "元");
                    Glide.with(context)
                            .load(userInfoBean.getUser().getAvatar())
                            .dontAnimate()
                            .error(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(head_photo);
                    helper.setText(R.id.state, "已奖励");
                }
            }
        };

        listview.setAdapter(quickAdapter);

        listview.setFocusable(false);
    }

    @Override
    protected void initData() {

        showDialog(context, null);

        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean userInfoBean) {
                dismissDialog();
                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                    MineWalletActivity.this.userInfoBean = userInfoBean;
                    money.setText(userInfoBean.getUser().getBalance().stripTrailingZeros().toPlainString() + "");
                } else {
                    if (userInfoBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(userInfoBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });


        finalOkGo.requestHead(RequestType.POSTHEAD, Url.MINE_WALLET_RULE, null, Url.MINE_WALLET_RULE, new Callback<SplashBean>() {
            @Override
            public void onSuccess(SplashBean splashBean) {
                dismissDialog();
                if (splashBean.getCode() == Contacts.SUCCESS) {
                    mSplashBean = splashBean;
                } else {
                    if (splashBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(splashBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                dismissDialog();
            }
        });

        requestData();
    }

    private void requestData() {
        HttpParams params = new HttpParams();
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.WALLET_LIST, params, Url.WALLET_LIST, new Callback<WalletListBean>() {
            @Override
            public void onSuccess(WalletListBean walletListBean) {
                if (walletListBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        quickAdapter.addAll(walletListBean.getPage().getList());
                    } else {
                        quickAdapter.addAll(walletListBean.getPage().getList());
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (walletListBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = walletListBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = walletListBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (walletListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(walletListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }

    //    @Override
    @OnClick({R.id.rule, R.id.cash, R.id.right_tv})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.rule:
                if (mSplashBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "奖励规则");
                    bundle.putString("url", mSplashBean.getUrl());
                    startActivity(RuleWebviewActivity.class, bundle);
                }
                break;
            case R.id.cash:
                if ((userInfoBean.getUser().getBalance().compareTo(new BigDecimal(5))) > -1) {
                    startActivity(CashActivity.class);
                } else {
                    showImageToas("余额不足5元无法提现，快去用能量值兑换吧");
                }
                break;
            case R.id.right_tv:
                startActivity(SignActivity.class);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        requestData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.contains("refresh_wallet")) {
            userInfoBean.getUser().setBalance(userInfoBean.getUser().getBalance().subtract(new BigDecimal(event.split(":")[1])));
            money.setText(userInfoBean.getUser().getBalance().stripTrailingZeros().toPlainString() + "");
        }
    }
}
